#encoding: utf-8
namespace :import_words do
  desc "从txt导入英语单词"
  task :import_words => :environment do
    path = "/Users/Admin/Documents/baicizhan/range_word/public/book_words"
    files = Dir.entries(path)
    puts "共有#{files.size}本书需要处理"
    files.each do |file|
      next if file.start_with?('.')
          filename = file.split('.')[0]
          puts "正在处理#{filename}"
          book = Book.create(:book_name => filename)
          next unless book.valid?
          file_content = File.open("#{path}/#{filename}.txt","r")
          while line = file_content.gets
            line = line.gsub(/\t/,"").gsub(/\n/,"")
            word = line.lstrip.rstrip
            next if word.blank?
            Word.create(:word => word,:book_id => book.id)
          end
          words_num = Word.find_all_by_book_id(book.id).size
          puts "录入#{words_num} words from #{book.book_name}"
      end
  end
end
